package com.yozinga.util;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.yozinga.fragment.HomePageFragment.EvalReceiver;

public class LocationManager implements OnConnectionFailedListener ,ConnectionCallbacks{
	private Double mLatitiude,mLongitude;
	public Location mLocation;
	private Context mContext;
	private LocationClient client;
	EvalReceiver mEvalReceiver;
	SharedData mSharedData;
	public LocationManager(Context context) {
		mContext = context;
		if(mContext!=null)
			mSharedData = new  SharedData(mContext);
	}

	public void getLocations(EvalReceiver evalReceiver) {
		mEvalReceiver = evalReceiver;
		if(mContext!=null){
			client = new LocationClient(mContext, this, this);
			client.connect();
		}
	}

	public void onConnected(Bundle connectionHint) {

		LocationRequest lRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
		LocationListener mLocationListener = new LocationListener() {

			public void onLocationChanged(Location location) {
				mLatitiude = location.getLatitude();
				mLongitude = location.getLongitude();
				mSharedData.setLocationValues(Double.toString(mLatitiude), Double.toString(mLongitude));
				Log.i("Team","Latitude is :"+mLatitiude+"Longitude :"+mLongitude);
				if(mLatitiude!=null && mLongitude!=null){
					Log.i("Today","Conver lat long to address");
					(new GetAddressTask(mContext,mEvalReceiver)).execute(location);
				}else{
					ResultReceiver receiver = mEvalReceiver;
					Bundle data = new Bundle();
					data.putSerializable("address", "Current Location Not Found");
					if (receiver != null) {
						receiver.send(1, data);
					}
				}
			}
		};

		client.requestLocationUpdates(lRequest, mLocationListener);

	}

	public void onDisconnected() {

	}

	public void onConnectionFailed(ConnectionResult result) {

	}
}
